package com.xingongchang.baolebei.fragment;

import java.util.ArrayList;

import org.afinal.simplecache.ACache;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.R.bool;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.Toast;

import com.external.androidquery.callback.AjaxStatus;
import com.external.maxwin.view.XListView;
import com.external.viewpagerindicator.PageIndicator;
import com.insthub.BeeFramework.fragment.BaseFragment;
import com.insthub.BeeFramework.model.BusinessResponse;
import com.insthub.BeeFramework.view.ToastView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.umeng.analytics.MobclickAgent;
import com.xingongchang.babyrecord.adapter.BannerPagerAdapter;
import com.xingongchang.baolebei.BaolebeiApp;
import com.xingongchang.baolebei.R;
import com.xingongchang.baolebei.activity.TanDatilactivity;
import com.xingongchang.baolebei.activity.TopicDetailActivity;
import com.xingongchang.baolebei.adapter.MorePopWindow;
import com.xingongchang.baolebei.model.ProtocolConst;
import com.xingongchang.baolebei.model.UserInfoModel;
import com.xingongchang.baolebei.protocol.AD;
import com.xingongchang.baolebei.protocol.CATEGORY;
import com.xingongchang.baolebei.protocol.SESSION;
import com.xingongchang.baolebei.protocol.User_tan;

//,OnTouchListener
public class Forumfrag extends BaseFragment implements OnClickListener,
		BusinessResponse, XListView.IXListViewListener
{
	private ImageLoader imageLoader;
	private View view, headerView;
	private MorePopWindow morePopWindow;
	private ImageView imageView, tan_tips;
	private UserInfoModel mUserInfoModel;
	private XListView xlistView;
	private boolean isSetAdapter = true;
	private SharedPreferences shared;
	private SharedPreferences.Editor editor;
	private String uid;
	private ViewPager viewPager;
	private ArrayList<View> bannerViews;// 滑动的图片集合
	private PageIndicator mIndicator;
	int count = 0;
	int total = 0;
	ImageView iamgeView;
	private FourAdapter adapter;
	private BannerPagerAdapter adapter2;
	private boolean isContinue = true;
	DisplayImageOptions options;
	ACache aCache;
	NetworkInfo mNetworkInfo;// 判断网络是否连接
	public ArrayList<User_tan> user_tanarraTans = new ArrayList<User_tan>();
	public ArrayList<AD> usds = new ArrayList<AD>();
    boolean iswife=false;
    ConnectivityManager mConnectivityManager;
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		imageLoader = ImageLoader.getInstance();
		options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.default_image)
				.showImageForEmptyUri(R.drawable.default_image)
				.showImageOnFail(R.drawable.default_image).cacheInMemory(true)
				.cacheOnDisk(true).considerExifParams(true)
				.bitmapConfig(Bitmap.Config.RGB_565).build();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState)
	{
		view = inflater.inflate(R.layout.luntan, null);
		imageLoader.init(ImageLoaderConfiguration.createDefault(getActivity()));
		shared = getActivity().getSharedPreferences("userInfo", 0);
		editor = shared.edit();
		// 缓存
		aCache = ACache.get(getActivity());
		// 判断是否连接网络
		mConnectivityManager= (ConnectivityManager) getActivity()
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
		headerView = LayoutInflater.from(getActivity()).inflate(
				R.layout.textview, null);
		viewPager = (ViewPager) headerView.findViewById(R.id.Tan_viewpager);
		android.widget.FrameLayout.LayoutParams params = (android.widget.FrameLayout.LayoutParams) viewPager
				.getLayoutParams();
		params.width = getDisplayMetricsWidth();
		params.height = (int) (params.width * 1.0 / 32 * 13);
		viewPager.setLayoutParams(params);
		bannerViews = new ArrayList<View>();
		mIndicator = (PageIndicator) headerView.findViewById(R.id.tan_intss);
		tan_tips = (ImageView) view.findViewById(R.id.Tan_tips);
		xlistView = (XListView) view.findViewById(R.id.Tan_parent_list);
		xlistView.setPullLoadEnable(false);// 有加载
		xlistView.setPullRefreshEnable(true);// 无加载更多
		xlistView.setRefreshTime();
		xlistView.addHeaderView(headerView);
		xlistView.setXListViewListener(this, 1);
		// 论坛登录
		imageView = (ImageView) view.findViewById(R.id.Tan_login);
		mUserInfoModel = new UserInfoModel(getActivity());
		mUserInfoModel.addResponseListener(this);
		if (mNetworkInfo!= null && mNetworkInfo.isConnected())
		{
			if (mNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI
					|| mNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE)
			{
				mUserInfoModel.getAd();
				SESSION session = SESSION.getInstance();
				mUserInfoModel.getTopicUserInfo(session.uid);
				mUserInfoModel.getLetter();
				mUserInfoModel.Forum();
				adapter2 = new BannerPagerAdapter(bannerViews);
				viewPager.setAdapter(adapter2);
				viewPager.setCurrentItem(0);
				mIndicator.setViewPager(viewPager);
				addBannerView();
			}
		}
		adapter2 = new BannerPagerAdapter(bannerViews);
		viewPager.setAdapter(adapter2);
		viewPager.setCurrentItem(0);
		mIndicator.setViewPager(viewPager);
		imageView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				mConnectivityManager= (ConnectivityManager) getActivity()
						.getSystemService(Context.CONNECTIVITY_SERVICE);
				mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
				if (mNetworkInfo == null)
				{
					ToastView toast = new ToastView(getActivity(),
							"网络异常，请检查网络设置");
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
				} else
				{
					morePopWindow = new MorePopWindow(getActivity(),
							mUserInfoModel.Usign);
					morePopWindow.showPopupWindow(imageView);
				}

			}
		});
		setAcshe();
		return view;
	}

	public void addBannerView()
	{
		total = mUserInfoModel.adList.size();
		count = 0;
		bannerViews.clear();
		for (int i = 0; i < mUserInfoModel.adList.size(); i++)
		{
			final AD ad = mUserInfoModel.adList.get(i);
			iamgeView = new ImageView(getActivity());
			iamgeView.setScaleType(ScaleType.CENTER_CROP);
			imageLoader.displayImage(ad.imgUrl, iamgeView, BaolebeiApp.options);
			iamgeView.setTag(ad);
			bannerViews.add(iamgeView);
			iamgeView.setOnClickListener(new OnClickListener()
			{

				@Override
				public void onClick(View v)
				{
					Intent intent = new Intent(getActivity(),
							TopicDetailActivity.class);
					intent.putExtra("topicid", ad.topicid);
					startActivity(intent);
				}
			});

		}

		mIndicator.notifyDataSetChanged();
		adapter2.mListViews = bannerViews;
		viewPager.setAdapter(adapter2);
		viewPager.setOnPageChangeListener(new OnPageChangeListener()
		{

			@Override
			public void onPageSelected(int arg0)
			{
				// TODO Auto-generated method stub
				count = arg0;
				mIndicator.setCurrentItem(arg0);
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2)
			{
				// TODO Auto-generated method stub

			}

			@Override
			public void onPageScrollStateChanged(int arg0)
			{
				// TODO Auto-generated method stub

			}
		});
		viewPager.setCurrentItem(count);
		handler.removeCallbacks(runnable);
		handler.postDelayed(runnable, 5000);

	}

	Runnable runnable = new Runnable()
	{
		@Override
		public void run()
		{
			count++;
			if (total == count)
			{
				count = 0;
			}
			viewPager.setCurrentItem(count);
			handler.postDelayed(this, 5000);
		}
	};
	// 切换当前显示的图片
	private Handler handler = new Handler()
	{
		public void handleMessage(android.os.Message msg)
		{
		};
	};

	@Override
	public void onDestroy()
	{
		super.onDestroy();
	}

	@Override
	public void onResume()
	{
		super.onResume();
		MobclickAgent.onPageStart("Profile");
		mConnectivityManager= (ConnectivityManager) getActivity()
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
		if(mNetworkInfo!= null && mNetworkInfo.isConnected()){
			
		if (mNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI
				||mNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE)
		{
			mUserInfoModel.getAd();
			mUserInfoModel.getLetter();
			mUserInfoModel.Forum();
		}
		}
	}

	@Override
	public void onRefresh(int id)
	{
		isSetAdapter = true;
		uid = shared.getString("uid", "");
		mConnectivityManager= (ConnectivityManager) getActivity()
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
		if(mNetworkInfo!= null && mNetworkInfo.isConnected()){
			
		if (mNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI
				||mNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE)
		{
			mUserInfoModel.getAd();
			mUserInfoModel.getLetter();
			mUserInfoModel.Forum();
			if (!uid.equals(""))
			{
				SESSION session = SESSION.getInstance();
				mUserInfoModel.getTopicUserInfo(session.uid);
				mUserInfoModel.addResponseListener(Forumfrag.this);
			}
		}
		}
		// mUserInfoModel.getAd();
		// mUserInfoModel.getLetter();
		// mUserInfoModel.Forum();
	}

	@Override
	public void onLoadMore(int id)
	{
	}

	@Override
	public void onClick(View arg0)
	{

	}

	public void OnMessageResponse(String url, JSONObject jo, AjaxStatus status)
			throws JSONException
	{
		// 论坛图片
		if (url.endsWith(ProtocolConst.AD))
		{
			addBannerView();
		}
		// 判断是否有私信未读
		if (url.endsWith(ProtocolConst.USER_STATUS_LETTER))
		{
			if (mUserInfoModel.Usign == 1)
			{
				tan_tips.setVisibility(View.VISIBLE);
			} else
			{
				tan_tips.setVisibility(View.GONE);
			}
		}
		if (url.endsWith(ProtocolConst.USER_TAN))
		{
			if (mUserInfoModel.responseStatus.succeed == 1)
			{
				xlistView.stopRefresh();
				xlistView.setRefreshTime();
				setContent();
				xlistView.setOnItemClickListener(new OnItemClickListener()
				{
					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int position, long arg3)
					{
						int topicId = mUserInfoModel.user_tanarraTans
								.get(position - 2).cat_id;
						String tanname = mUserInfoModel.user_tanarraTans
								.get(position - 2).cat_name;
						String img = mUserInfoModel.user_tanarraTans
								.get(position - 2).thumb;
						String desc = mUserInfoModel.user_tanarraTans
								.get(position - 2).cat_desc;
						Intent intent = new Intent(getActivity(),
								TanDatilactivity.class);
						intent.putExtra("topicid", topicId);
						intent.putExtra("name", tanname);
						intent.putExtra("Imgs", img);
						intent.putExtra("descname", desc);
						startActivity(intent);

					}
				});
			}
		}

	}

	public void setContent()
	{

		if (adapter == null)
		{

			if (mUserInfoModel.user_tanarraTans.size() != 0)
			{
				adapter = new FourAdapter(getActivity(),
						mUserInfoModel.user_tanarraTans, options);
				xlistView.setAdapter(adapter);
			}

		} else
		{

			if (isSetAdapter == true)
			{
				xlistView.setAdapter(adapter);
			} else
			{
				adapter.list = mUserInfoModel.user_tanarraTans;
				adapter.notifyDataSetChanged();
			}
		}

	}

	public void setAcshe()
	{
		if (mConnectivityManager.getActiveNetworkInfo() == null)
		{
			isSetAdapter = false;
			// 当前分类
			JSONArray jsonObject = aCache.getAsJSONArray("categoryData");
			if (null != jsonObject && jsonObject.length() > 0)
			{
				for (int i = 0; i < jsonObject.length(); i++)
				{
					JSONObject categoryObject;
					try
					{
						categoryObject = jsonObject.getJSONObject(i);
						User_tan category = User_tan.fromJson(categoryObject);

						user_tanarraTans.add(category);
					} catch (JSONException e)
					{
						e.printStackTrace();
					}
				}
			}
			if (user_tanarraTans.size() != 0)
			{
				if (adapter == null)
				{
					adapter = new FourAdapter(getActivity(), user_tanarraTans,
							options);
					xlistView.setAdapter(adapter);
				} else
				{
					adapter.list = user_tanarraTans;
					adapter.notifyDataSetChanged();
				}
				xlistView.setAdapter(adapter);
				xlistView.stopRefresh();
				xlistView.setRefreshTime();
				xlistView.stopLoadMore();
				xlistView.setOnItemClickListener(new OnItemClickListener()
				{
					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int position, long arg3)
					{
						int topicId = user_tanarraTans
								.get(position - 2).cat_id;
						String tanname = user_tanarraTans
								.get(position - 2).cat_name;
						String img = user_tanarraTans
								.get(position - 2).thumb;
						String desc = user_tanarraTans
								.get(position - 2).cat_desc;
						Intent intent = new Intent(getActivity(),
								TanDatilactivity.class);
						intent.putExtra("topicid", topicId);
						intent.putExtra("name", tanname);
						intent.putExtra("Imgs", img);
						intent.putExtra("descname", desc);
						startActivity(intent);


					}
				});
			}
			// 当前广告
			JSONArray adJsonArray = aCache.getAsJSONArray("adverta");
			if (null != adJsonArray && adJsonArray.length() > 0)
			{
				usds.clear();
				for (int i = 0; i < adJsonArray.length(); i++)
				{
					JSONObject adJsonObject;
					try
					{

						adJsonObject = adJsonArray.getJSONObject(i);
						AD ad = AD.fromJson(adJsonObject);
						usds.add(ad);
					} catch (JSONException e)
					{
						e.printStackTrace();
					}
				}
			}
			total = usds.size();
			count = 0;
			bannerViews.clear();
			for (int i = 0; i < usds.size(); i++)
			{
				final AD ad = usds.get(i);
				iamgeView = new ImageView(getActivity());
				iamgeView.setScaleType(ScaleType.CENTER_CROP);
				imageLoader.displayImage(ad.imgUrl, iamgeView,
						BaolebeiApp.options);
				iamgeView.setTag(ad);
				bannerViews.add(iamgeView);
				iamgeView.setOnClickListener(new OnClickListener()
				{

					@Override
					public void onClick(View v)
					{
						Intent intent = new Intent(getActivity(),
								TopicDetailActivity.class);
						intent.putExtra("topicid", ad.topicid);
						startActivity(intent);
					}
				});

			}
			mIndicator.notifyDataSetChanged();
			adapter2.mListViews = bannerViews;
			viewPager.setAdapter(adapter2);
			viewPager.setOnPageChangeListener(new OnPageChangeListener()
			{

				@Override
				public void onPageSelected(int arg0)
				{
					// TODO Auto-generated method stub
					count = arg0;
					mIndicator.setCurrentItem(arg0);
				}

				@Override
				public void onPageScrolled(int arg0, float arg1, int arg2)
				{

				}

				@Override
				public void onPageScrollStateChanged(int arg0)
				{

				}
			});
			viewPager.setCurrentItem(count);
			handler.removeCallbacks(runnable);
			handler.postDelayed(runnable, 5000);
		} else
		{
			isSetAdapter = true;
		}
	}

	// 获取屏幕宽度
	public int getDisplayMetricsWidth()
	{
		int i = getActivity().getWindowManager().getDefaultDisplay().getWidth();
		int j = getActivity().getWindowManager().getDefaultDisplay()
				.getHeight();
		return Math.min(i, j);
	}
}
